<template>
  <div class="fba-print-wrap">
    <div class="print-setting">
      <a-scrollbar style="height: 100%; overflow: auto">
        <ChoosePrintList :selectWidth="210" ref="choosePrintRef" style="margin-bottom: 10px" @getLodop="getLodop">
          <template #ipUrl>
            <p class="label">选择云主机：</p>
          </template>
          <template #bridgelabel>
            <p class="label">选择端桥：</p>
          </template>
          <template #printerlabel>
            <p class="label">选择打印机：</p>
          </template>
        </ChoosePrintList>
        <div class="set-item flex-c">
          <p class="label">打印份数：</p>
          <a-input-number size="small" v-model="printNum" :min="1" />
          <span class="unit">份</span>
        </div>
        <div class="set-item" style="margin-top: 30px">
          <p style="font-weight: bold; margin-bottom: 10px">选择打印模板：</p>
          <a-dropdown position="bl" trigger="hover">
            <a-button class="gray-outline flex-c-sb" style="min-width: 160px"> {{ currentTemp.templateName || '默认模板' }} <icon-down /> </a-button>
            <template #content>
              <a-doption @click="resetTemp">默认模板</a-doption>
              <a-doption v-for="(item, i) in tempList" :key="i" @click="changeTemplate(item)">{{ item.templateName }}</a-doption>
            </template>
          </a-dropdown>
        </div>
        <div class="set-item" style="margin-top: 10px">
          <p style="font-weight: bold; margin-bottom: 10px">图片尺寸：</p>
          <ul class="img-size-list">
            <li v-for="size in imgSizeList" :key="size" @click="editForm.imgSize = size" :style="{ width: size + 'px', height: size + 'px' }" :class="{ active: editForm.imgSize == size }">{{ size }}</li>
          </ul>
        </div>
        <div class="set-item" style="margin-top: 20px">
          <p>
            <span style="font-weight: bold">可选字段：</span>
            <span style="color: #999">最多可选7项</span>
          </p>
          <a-checkbox-group v-model="editForm.fieldList">
            <p style="margin: 10px 0 5px">单据字段：</p>
            <a-checkbox style="width: 105px; margin-right: 5px" v-for="(key, val) in billFieldList" :key="val" :value="val">{{ key }}</a-checkbox>
          </a-checkbox-group>
          <a-checkbox-group v-model="editForm.propsFieldList">
            <p style="margin: 10px 0 5px">产品属性：</p>
            <a-checkbox style="width: 105px; margin-right: 5px" v-for="(val, key) in propFieldMap" :key="key" :value="val.code">{{ val.name }}</a-checkbox>
          </a-checkbox-group>
        </div>
        <div class="bill-total">
          <p style="font-weight: bold; margin-bottom: 10px">打印单据：</p>
          <a-table :data="pdfList" size="mini" :bordered="{ cell: true }" :pagination="false">
            <template #columns>
              <a-table-column title="序号">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="单据号" data-index="billNo" />
              <a-table-column title="行数" data-index="skuType" />
            </template>
          </a-table>
        </div>
      </a-scrollbar>

      <div class="handle-btn-w">
        <a-space>
          <a-button class="gray-outline" size="medium" @click="closePage">取消打印</a-button>
          <AddPrintTemp :currentTemp="currentTemp" templateCode="PRINT_APPLICATION_IN_STORAGE_PDF" :content="editForm" @success="getTemplateList" />
          <a-button type="primary" size="medium" @click="toPrintPre" :loading="submitLoading">确认打印</a-button>
        </a-space>
      </div>
    </div>
    <div class="fba-list-w">
      <div id="test"> </div>
      <div class="fba-item-w" v-for="(item, i) in pdfList" :key="i">
        <div class="header flex-c">
          <h2>入库单</h2>
          <img :src="brcode" />
          <h3>{{ item.billNo }}</h3>
        </div>
        <div class="print-header flex-c">
          <p style="width: 120px; margin-right: 40px">打印人：{{ userStore.userName }}</p>
          <p style="width: 300px; margin-right: 40px">打印时间：{{ dayjs().format('YYYY-MM-DD HH:mm:ss') }}</p>
        </div>
        <div class="fba-header">
          <p style="width: 30%">
            <span class="label">采购方：</span>
            <span>{{ item.purchaseOrgName }}</span>
          </p>
          <!-- <p style="width: 15%">
            <span class="label">采购员：</span>
            <span>{{ item.purchaseUname }}</span>
          </p> -->
          <p style="width: 30%">
            <span class="label">申购方：</span>
            <span>{{ item.companyName }}</span>
          </p>
          <p style="width: 20%">
            <span class="label">申购人：</span>
            <span>{{ item.salesmanName }}</span>
          </p>
          <p style="width: 20%">
            <span class="label">合计数量：</span>
            <span>{{ item.skuType }}SKU，{{ item.status == 30 ? item.warehouseRealAmt : item.warehouseAmt }}件</span>
          </p>
          <p style="width: 30%">
            <span class="label">仓库：</span>
            <span>{{ item.warehouseName }}({{ item.warehouseCode }})</span>
          </p>
          <p style="width: 70%">
            <span class="label">仓库地址：</span>
            <span>{{ item.receivingAddress }}</span>
          </p>
        </div>
        <a-table :data="item.billItems" size="mini" :bordered="{ cell: true }" :pagination="false">
          <template #columns>
            <a-table-column v-for="list of defaultField" :key="list.key" :title="list.name" :data-index="list.key">
              <template v-if="list.key == 'sort'" #cell="{ rowIndex }">
                <p>{{ rowIndex + 1 }}</p>
              </template>
              <template v-else-if="list.key == 'productImg'" #cell="{ record }">
                <ImgPopover :src="record.productImg">
                  <template #con>
                    <a-image :width="editForm.imgSize" :height="editForm.imgSize" fit="contain" :src="record.productImg" />
                  </template>
                </ImgPopover>
              </template>
            </a-table-column>
            <!-- 自定义新增的固定字段 -->
            <a-table-column v-for="(key, j) of editForm.fieldList" :key="key" :data-index="key">
              <template #title>
                <div class="flex-c">
                  <p>{{ billFieldList[key] }}</p>
                  <icon-close class="cursor" @click="editForm.fieldList.splice(j, 1)" style="margin-left: 4px" />
                </div>
              </template>
              <template #cell="{ record }" v-if="key == 'specValue'">
                <p>{{ getProductSpecs(record) }}</p>
              </template>
              <template #cell="{ record }" v-else-if="key == 'warehouseAmt'">
                <p>{{ record.status == 30 ? record.warehouseRealAmt : record.warehouseAmt }}</p>
              </template>
              <template #cell="{ record }" v-else-if="key == 'materialWeight'">
                <p>{{ record.status == 30 ? record.materialRealWeight : record.materialWeight }}</p>
              </template>
            </a-table-column>
            <!-- 自定义新增的属性字段 -->
            <a-table-column v-for="(key, l) of editForm.propsFieldList" :key="key" :data-index="key">
              <template #title>
                <div class="flex-c">
                  <p>{{ propFieldMap[key] ? propFieldMap[key].name : '' }}</p>
                  <icon-close class="cursor" @click="editForm.propsFieldList.splice(l, 1)" style="margin-left: 4px" />
                </div>
              </template>
              <template #cell="{ record }">
                <p>{{ getCurrentProp(record, key) }}</p>
              </template>
            </a-table-column>
          </template>
        </a-table>
        <p class="footer-page">第1页/共1页</p>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import brcode from '@/assets/brcode.png'
  import { useRouter, useRoute } from 'vue-router'
  import useVisitedRouteStore from '@/store/modules/visited-routes'
  import useUserStore from '@/store/modules/user'
  import dayjs from 'dayjs'
  import { getRelatedList } from '@/api/product'
  import { findReceiptByPurchasePage } from '@/api/purchaseApplication'
  import { parseJson, getStrVal } from '@/utils'
  import ChoosePrintList from '@/components/Print/choosePrintList.vue'
  import { findTemplateList } from '@/api/export'
  onMounted(async () => {
    getPdfList()
    getPropsList()
    await getTemplateList()
    if (tempList.value.length) {
      changeTemplate(tempList.value[0])
    }
  })

  const visitedRouteStore = useVisitedRouteStore()
  const route = useRoute()
  const router = useRouter()
  const pdfList = ref<Array<any>>([])
  const tableLoading = ref(false)
  const submitLoading = ref(false)
  const userStore = useUserStore()
  const printNum = ref(1)
  const editForm = ref<any>({
    imgSize: 60,
    fieldList: ['sku', 'warehouseAmt', 'cateName'],
  })
  const imgSizeList = ['80', '60', '44', '32']

  const billFieldList = {
    sku: 'SKU',
    warehouseAmt: '数量',
    materialWeight: '材质重量(g)',
    specValue: 'SKU规格',
    cateName: '类目',
    remark: '备注',
    purchaseUname: '采购员',
  }
  const propFieldMap = ref<any>({})
  const choosePrintRef = ref()
  const currentTemp = ref<any>({})
  const tempList = ref<Array<any>>([])

  const defaultField = [
    {
      name: '序号',
      key: 'sort',
    },
    {
      name: '图片',
      key: 'productImg',
    },
  ]
  let LODOP: any = {}

  // 获取打印列表
  async function getPdfList() {
    pdfList.value = []
    let ids = window.sessionStorage.getItem('applicationInStorageId')
    if (!ids?.length) return
    tableLoading.value = true
    const res: any = await findReceiptByPurchasePage({
      ids,
      pageSize: 1000,
      pageNum: 1,
    })
    tableLoading.value = false
    let list = res?.data?.records || []
    list.forEach((el: any) => {
      el.billItems.forEach((item: any) => {
        item.purchaseSpecs = item.purchaseSpecs ? parseJson(item.purchaseSpecs, {}) : {}
      })
    })
    pdfList.value = list
  }
  //获取导出模板
  async function getTemplateList() {
    const res: any = await findTemplateList({ templateType: 2, templateCode: 'PRINT_APPLICATION_IN_STORAGE_PDF' })
    tempList.value = res?.data || []
  }
  //切换模板
  function changeTemplate(item: any) {
    currentTemp.value = item
    editForm.value = parseJson(item.templateContent, [])
  }
  function resetTemp() {
    currentTemp.value = {}
    editForm.value = {
      imgSize: 60,
    }
  }
  // 获取所有属性列表
  async function getPropsList() {
    const res: any = await getRelatedList({
      pageSize: 1000,
      pageNum: 1,
    })
    propFieldMap.value = {}
    let list = res?.data?.records || []
    list.forEach((el: any) => {
      propFieldMap.value[el.code] = el
    })
  }
  // 获取当前sku的属性值
  function getCurrentProp(row: any, key: string) {
    let purchaseValue = row.purchaseSpecs?.[key]?.purchaseValue
    return getStrVal(purchaseValue)
  }
  // 显示sku规格
  function getProductSpecs(item: any) {
    let productSpecs = item.productSpecs ? parseJson(item.productSpecs, []) : []
    return productSpecs.map((el: any) => el.valueCn)?.join('*') || '--'
  }
  // 获取所有自定义显示字段
  function getFilxedList() {
    let list: Array<any> = []
    editForm.value.fieldList?.forEach((key: string) => {
      list.push({ name: billFieldList[key], key: key, type: 1 })
    })
    editForm.value.propsFieldList?.forEach((key: string) => {
      list.push({ name: propFieldMap.value[key]?.name, key: key, type: 2 })
    })
    return [...defaultField, ...list]
  }

  // 关闭界面
  function closePage() {
    visitedRouteStore.removeVisitedRoute(route)
    router.go(-1)
  }
  // 设置打印表格内容
  function getPrintTable(row: any) {
    let theadTd = ''
    let filxedList = getFilxedList()
    filxedList.forEach((item: any) => {
      theadTd += `<td style="min-height:30px;background-color:#ddd"><div align=center>${item.name}</div></td>`
    })
    let tbodyTr = ``
    row.billItems.forEach((skuItem: any, index: number) => {
      let td = ''
      filxedList.forEach((item: any) => {
        if (item.type == 2) {
          // 属性
          td += `<td><p align=center>${getCurrentProp(skuItem, item.key)}</p></td>`
        } else if (item.key == 'warehouseAmt') {
          td += `<td><p align=center>${skuItem.status == 30 ? skuItem.warehouseRealAmt : skuItem.warehouseAmt}</p></td>`
        } else if (item.key == 'materialWeight') {
          td += `<td><p align=center>${skuItem.status == 30 ? skuItem.materialRealWeight : skuItem.materialWeight}</p></td>`
        } else if (item.key == 'sort') {
          td += `<td><p align=center>${index + 1}</p></td>`
        } else if (item.key == 'productImg') {
          td += `<td align=center><div style="width:${editForm.value.imgSize}px;height:${editForm.value.imgSize}px"><img src="${skuItem.productImg}" width="${editForm.value.imgSize}" /></div></td>`
        } else if (item.key == 'specValue') {
          td += `<td align=center><p align=center>${getProductSpecs(skuItem)}</p></td>`
        } else {
          td += `<td><p align=center>${skuItem[item.key] || '--'}</p></td>`
        }
      })
      tbodyTr += `<tr>${td}</tr>`
    })
    return `
    <table border=1 cellSpacing=0 cellPadding=1 width="100%" style="border-collapse:collapse;font-size:14px" bordercolor="#333333">
      <thead>
        <tr>${theadTd}</tr>
      </thead>
      <tbody>
        ${tbodyTr}
      </tbody>
    </table>
    `
  }
  // 设置打印的表头
  function getPrintHeader(row: any) {
    return `
      <div style="height: 30px; display: flex;width:100%">
        <p style="width: 120px; margin-right: 40px;font-size:14px">打印人：${userStore.userName}</p>
        <p style="width: 300px; margin-right: 40px;font-size:14px">打印时间：${dayjs().format('YYYY-MM-DD HH:mm:ss')}</p>
      </div>
      <div style="height:8px"></div>
      <div style="background-color: #ccc; padding: 5px;">
        <table border="0" cellSpacing="0" cellPadding="0" width="100%">
          <tbody>
            <tr>
              <td width="30%">
                <p style="font-size:14px;line-height:24px;">
                  <span style="colot:#ccc;">采购方：</span><span>${row.purchaseOrgName || '--'}</span>
                </p>
              </td>
              <td width="30%">
                <p style="font-size:14px;line-height:24px;">
                  <span style="colot:#ccc;">申购方：</span><span>${row.companyName || '--'}</span>
                </p>
              </td>
              <td width="20%">
                <p style="font-size:14px;line-height:24px;">
                  <span style="colot:#ccc;">申购人：</span><span>${row.salesmanName || '--'}</span>
                </p>
              </td>
              <td width="20%">
                <p style="font-size:14px;line-height:24px;">
                  <span style="colot:#ccc;">合计数量：</span><span>${row.skuType}SKU，${row.status == 30 ? row.warehouseRealAmt : row.warehouseAmt}件</span>
                </p>
              </td>
            </tr>
            <tr>
              <td colspan="1">
                <p style="font-size:14px;line-height:24px;">
                  <span style="colot:#ccc;">仓库：</span><span>${row.warehouseName}(${row.warehouseCode})</span>
                </p>
              </td>
              <td colspan="3">
                <p style="font-size:14px;line-height:24px;">
                  <span style="colot:#ccc;">仓库地址：</span><span>${row.receivingAddress || '--'}</span>
                </p>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      `
  }
  function getLodop(val: any) {
    LODOP = val
  }
  function addPrint() {
    // 纸张初始化
    LODOP.PRINT_INIT('打印申购入库单')
    // 横向打印
    LODOP.SET_PRINT_PAGESIZE(2)

    //  指定打印机设备
    let { type, bridgeIDandName, printerIndex } = choosePrintRef.value.getBridgeInfo()
    if (type === 1) {
      LODOP.SET_BRIDGE_INDEX(bridgeIDandName + ',' + printerIndex)
    } else {
      LODOP.SET_PRINTER_INDEX(printerIndex)
    }

    LODOP.SET_SHOW_MODE('LANDSCAPE_DEFROTATED', 1)
    var strStyle = '<style> table,td,th {border-width: 1px;border-style: solid;border-collapse: collapse}</style>'
    pdfList.value.forEach((item: any, index: number) => {
      // 头部打印信息
      let headerHtml = getPrintHeader(item)
      let innerHTML = getPrintTable(item)

      if (index > 0) {
        LODOP.NewPageA()
      }
      // table
      LODOP.ADD_PRINT_TABLE('40mm', '1%', '97%', 390, strStyle + innerHTML)
      LODOP.SET_PRINT_STYLEA(0, 'Vorient', 3)
      LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', index * 6 + 1)

      LODOP.SET_PRINT_STYLE('FontSize', 14)
      LODOP.SET_PRINT_STYLE('Bold', 1)

      // 标题
      LODOP.ADD_PRINT_TEXT('3.5%', '1%', '20mm', '6mm', '入库单')
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)
      LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', index * 6 + 1)

      // 条形码
      LODOP.ADD_PRINT_BARCODE('2%', '20mm', '40mm', '10mm', '128B', item.billNo)
      LODOP.SET_PRINT_STYLEA(0, 'ShowBarText', 0)
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)

      // 单号
      LODOP.ADD_PRINT_TEXT('3.5%', '65mm', 200, 40, item.billNo)
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)
      LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', index * 6 + 1)

      LODOP.SET_PRINT_STYLE('Bold', 0)
      LODOP.SET_PRINT_STYLE('FontSize', 10)

      // 头部基础信息
      LODOP.ADD_PRINT_HTML('12mm', '1%', '97%', 100, headerHtml)
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)
      LODOP.SET_PRINT_STYLEA(0, 'LinkedItem', index * 6 + 1)

      // 分页合计
      LODOP.ADD_PRINT_HTM('195mm', '45%', 200, 100, "<p style='font-size:12px'><span tdata='pageNO'>第##页</span>/<span tdata='pageCount'>共##页</span></p>")
      LODOP.SET_PRINT_STYLEA(0, 'ItemType', 1)

      LODOP.SET_PRINT_COPIES(printNum.value || 1)
    })
  }
  // 打印预览
  function toPrintPre() {
    addPrint()
    LODOP.PREVIEW()
  }
</script>
<style lang="less" scoped>
  .fba-print-wrap {
    display: flex;
    height: calc(100vh - @menuHeight);
    overflow: hidden;
    .print-setting {
      background-color: #fff;
      margin-right: 5px;
      height: 100%;
      flex-shrink: 0;
      width: 400px;
      position: relative;
      .arco-scrollbar {
        height: 100%;
        padding: 20px 20px 50px;
      }
      .title {
        font-size: 16px;
        margin-bottom: 20px;
        font-weight: bold;
      }
      :deep(.printer-w .label) {
        width: 100px;
        flex-shrink: 0;
        text-align: right;
        color: var(--color-text-1);
      }
      .set-item {
        margin-bottom: 15px;
        .label {
          width: 100px;
          text-align: right;
          flex-shrink: 0;
        }
        .unit {
          line-height: 30px;
          background-color: var(--color-fill-2);
          padding: 0 12px;
          margin-left: 10px;
        }
      }
      .img-size-list {
        flex: 1;
        display: flex;
        align-items: flex-end;
        justify-content: space-between;
        li {
          border: 1px solid #dadde2;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          &.active {
            border-color: rgb(var(--primary-6));
            color: rgb(var(--primary-6));
          }
        }
      }
      .handle-btn-w {
        position: absolute;
        width: 100%;
        bottom: 10px;
        right: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }
    .price-type {
      font-size: 12px;
      transform: scale(0.82);
      position: relative;
      left: -4px;
    }
    .priview-w {
      background-color: #fff;
      flex: 1;
    }
    .fba-list-w {
      flex: 1;
      height: calc(100vh - @menuHeight);
      overflow-y: auto;
      margin-left: 5px;
      .fba-item-w {
        background-color: #fff;
        margin-bottom: 10px;
        padding: 15px 15px 50px;
        min-height: 600px;
        position: relative;
        .header {
          font-weight: bold;
          h2 {
            font-size: 18px;
          }
          img {
            width: 160px;
            height: 30px;
            margin: 0 10px;
          }
        }
        .print-header {
          margin: 8px 0;
        }
        .fba-header {
          padding: 5px;
          background-color: var(--color-neutral-2);
          display: flex;
          flex-wrap: wrap;
          margin-bottom: 8px;
          p {
            width: 20%;
            line-height: 24px;
            .label {
              color: #999;
            }
          }
        }
        .footer-sum {
          background-color: var(--color-neutral-2);
          border-bottom: 1px solid var(--color-neutral-3);
          border-top: none;
          display: flex;
          flex-wrap: wrap;
          padding: 5px 10px;
          p {
            margin-right: 50px;
          }
        }
        .footer-page {
          position: absolute;
          bottom: 10px;
          font-size: 12px;
          left: 50%;
          transform: translate(-50%);
        }
      }
    }
  }
</style>
